#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<assert.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<stdlib.h>
#define ARGV 64
#define MAX 1024
#define SEP " "

int split(char* commandstr,char* argv[])
{
  assert(commandstr);
  assert(argv);
  argv[0] = strtok(commandstr,SEP);
  if(argv == NULL)
    return -1;
  int i = 1;
  while(1)
  {
    argv[i] = strtok(NULL,SEP);
    if(argv[i] == NULL)
    {
      break;
    }
    i++;
  }
  return 0;
}

void debugPrint(char* argv[])
{
  int i = 0;
  for(i = 0;argv[i];i++)
  {
    printf("%d : %s \n",i,argv[i]);
  }
}

int main()
{
  char commandstr[MAX] = {0};
  char* argv[ARGV] = { NULL };
  while(1)
  {
    printf("[sweet  myshell]$ ");
    fflush(stdout);
    char* s = fgets(commandstr,sizeof(commandstr),stdin);
    assert(s);
    (void)s;
    commandstr[strlen(commandstr) - 1] = '\0';
    int n = split(commandstr,argv);
    if(n!=0)
      continue;
    //debugPrint(argv);
    if(strcmp(argv[0],"cd") == 0)
    {
      if(argv[1] != NULL) chdir(argv[1]);
      continue;
    }
    if(strcmp(argv[0],"ls") == 0)
    {
      int pos = 0;
      while(argv[pos])
      {
          pos++;
      }
      argv[pos++] = (char*)"--color=auto";
      argv[pos] = NULL;
    }
    pid_t id = fork();
    assert(id>=0);
    (void)id;
    if(id == 0)
    {
      execvp(argv[0],argv);
      exit(1);
    }
    int status = 0;
    waitpid(id,&status,0);
  }
  return 0;
}
